import axios from "axios";
import router from "@/router";
import Cookies from 'js-cookie'
import user from "@/views/user/User.vue";


const request = axios.create({
    baseURL:'http://localhost:9090/api',         //所有的接口都会加上api的前缀
    timeout:5000
})


request.interceptors.request.use(config => {
    config.headers['Content-Type'] ='application/json;charset=utf-8';

    const adminJSON = Cookies.get('admin')
    if (adminJSON) {       //当Cookies的值为空时并且当前的路由不在/login才发生跳转
        config.headers['token'] = JSON.parse(adminJSON).token
    }
    return config
},error => {
    return Promise.reject(error)
});

//response 拦截器
request.interceptors.response.use(
    response => {
        let res = response.data;
        if (typeof res == 'string') {
            res = res ? JSON.parse(res) : res
        }
        if (res.code === '401') {
            router.push('/login')
        }
        return res;
    },
    error => {
        console.log('err' + error)
        return Promise.reject(error)
    }
)

export default request